package com.achobeta.recruitment.component.handler;

import com.achobeta.recruitment.common.AppResult;
import com.achobeta.recruitment.controller.wx.WxController;
import com.achobeta.recruitment.utils.JsonUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 马拉圈
 * Date: 2023-10-02
 * Time: 1:20
 */
@RestControllerAdvice(basePackages = "com.achobeta.recruitment.controller")
public class ResponseAdvice implements ResponseBodyAdvice {


    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        // 排除特定的 Controller
        if(returnType.getDeclaringClass().equals(WxController.class)) {
            return false;
        }
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType,
                                  MediaType selectedContentType, Class selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        if(body instanceof AppResult) {
            return body;
        }
        if(body instanceof String) {
            return JsonUtils.objectToJson(AppResult.success(body));
        }
        return AppResult.success(body);
    }
}